#include "..\\include\Lib_Clara.h"
#include "..\\include\Dir.h"
#include "..\\include\cfg_items.h"
#include "conf_loader.h"

const wchar_t *successed_config_path=L"";
const wchar_t *successed_config_name=L"";

#pragma segment = "CONFIG_C"

int LoadConfigData(const wchar_t *path,const wchar_t *fname)
{
   FSTAT fbuf;
   char *buf = NULL;
   char *cfg = NULL;
   unsigned int rlen = 0;;
   unsigned int len  = 0;
   int fd;
   int result = -1;

   cfg = (char *) __segment_begin ( "CONFIG_C" );

   len = (char *) __segment_end ( "CONFIG_C" ) - cfg;

   if ( buf = new char[len] )
   {
      if ( fstat ( path, fname, &fbuf ) != -1 )
      {
         if ( fd = _fopen ( path, fname, 0x001, 0x180, 0) >= 0 )
         {
            rlen = fread ( fd, buf, len);
            fclose ( fd );
            if ( rlen != fbuf.fsize || rlen != len )
               goto L_SAVENEWCFG;
            memcpy ( cfg, buf, len );
            result = 0;
         }
      }
      else
      {
         L_SAVENEWCFG:
         if ( fd = _fopen ( path, fname, 0x204, 0x180, 0 ) >= 0 )
         {
            if ( fwrite ( fd, cfg, len ) == len )
               result = 0;
            fclose ( fd );
         }
      }
      delete buf;
   }
   if ( result >= 0 )
   {
      successed_config_path = path;
      successed_config_name = fname;
   }
   return result;
}

void InitConfig(void)
{
   if ( LoadConfigData ( GetDir ( DIR_ELFS_CONFIG | MEM_EXTERNAL ), L"MemoryViewer.bcfg" ) < 0 )
      LoadConfigData ( GetDir ( DIR_ELFS_CONFIG | MEM_INTERNAL ), L"MemoryViewer.bcfg" );
}
